package com.wy.service.impl.sys;

import com.wy.bean.HouseholdBean;
import com.wy.dao.*;
import com.wy.model.sys.Households;
import com.wy.model.sys.RelationEntity;
import com.wy.model.sys.Residence;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(value = "userServiceImpl")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private RelationDao relationDao;

	@Autowired
	private HouseholdsMapper householdDao;

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private ResidenceMapper residenceMapper;


	@Override
	public void insert(UserEntity userEntity) {
		userDao.insert(userEntity);
	}

	@Override
	public void del(UserEntity userEntity) {
		userDao.del(userEntity);
	}

	@Override
	public UserEntity getUserEntityByLoginName(String loginName) {
		return userDao.getUserByLoginName(loginName);
	}

	@Override
	public List<UserEntity> usersList(String loginName, int pageSize, int start) {
		return userDao.usersList( loginName,  pageSize,  start);
	}

	@Override
	public Integer usersSize(String loginName, int pageSize, int start) {
		return userDao.usersSize(loginName, pageSize, start);
	}

	@Override
	public Integer insertUser(UserEntity userEntity) {
//		String password = null;
//		try {
//			password = MD5Util.encrypt(userEntity.getPassword());
//			userEntity.setPassword(password);
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		}
//		userEntity.setPassword(new Md5PasswordEncoder().encodePassword(userEntity.getPassword(), null));
		userEntity.setPassword("{bcrypt}"+new BCryptPasswordEncoder().encode(userEntity.getPassword()));
		userEntity.setCreateTime(new Date());
		userEntity.setAuthTime(new Date());
		userDao.insertUser(userEntity);


		List<RelationEntity> relationEntityList = new ArrayList<RelationEntity>();
		RelationEntity relationEntity = new RelationEntity();
		relationEntity.setRoleId(2);
		relationEntity.setUserId(userEntity.getId());
		relationEntityList.add(relationEntity);
		relationDao.insertRelations(relationEntityList);

		return userEntity.getId();
	}

	/**
	 * 根据用户名密码添加住户
	 * @param loginName
	 * @param password
	 */
	@Override
	public void insertUser(String loginName, String password) {
		UserEntity userEntity = new UserEntity();
		userEntity.setLoginName(loginName); //用户名
		userEntity.setName(loginName);//用户名
		userEntity.setMobile(loginName);//手机号码
		userEntity.setPassword(password);
		userEntity.setStatus("0");
		userEntity.setAuthStatus("0");
		userEntity.setSource("1");
		userEntity.setCreateTime(new Date());
		userEntity.setPassword("{bcrypt}"+new BCryptPasswordEncoder().encode(userEntity.getPassword()));
		userDao.insertUser(userEntity);
		//添加用户角色关联表默认角色：普通住户
		List<RelationEntity> relationEntityList = new ArrayList<RelationEntity>();
		RelationEntity relationEntity = new RelationEntity();
		relationEntity.setRoleId(2);
		relationEntity.setUserId(userEntity.getId());
		relationEntityList.add(relationEntity);
		relationDao.insertRelations(relationEntityList);
	}

	@Override
	public void updateUser(UserEntity userEntity) {
//		String password = null;
//		try {
//			password = MD5Util.encrypt(userEntity.getPassword());
//			userEntity.setPassword(password);
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		}
//		userEntity.setPassword(new Md5PasswordEncoder().encodePassword(userEntity.getPassword(), null));
		UserEntity currentUser = userDao.getUserById(userEntity.getId());
		//如果没有改密码，也就是现在的密码和库里的密码一致，则不改此字段
		if(!currentUser.getPassword().equals(userEntity.getPassword())) {
			userEntity.setPassword("{bcrypt}" + new BCryptPasswordEncoder().encode(userEntity.getPassword()));
		}
		userDao.updateUser(userEntity);
	}

	@Override
	public void deleteUsers(List<String> groupId) {
		userDao.deleteUsers(groupId);
		relationDao.delete(groupId);
	}

	@Override
	public UserEntity getUserById(Integer userId) {
		return userDao.getUserById(userId);
	}

	@Override
	public UserEntity getUserByMobile(String mobile) {
		return userDao.getUserByMobile(mobile);
	}

	@Override
	public UserEntity getUserByLoginName(String loginName) {
		return userDao.getUserByLoginName(loginName);
	}

	@Override
	public Integer getUesrIdByLoginName(String loginName) {
		return userDao.getUesrIdByLoginName(loginName);
	}

	@Override
	public int modifyPasswordValidate(String newPassword, String oldPassword,String loginName) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		int flag = 0;//0 密码为空，-1 原密码输入错误，1 新旧密码相同 ，200 密码合法
		UserEntity userEntity = getUserByLoginName(loginName);
		String password =userEntity.getPassword();  //旧密码加密后
		if(StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)){
			return flag;
		}
		//判断原密码输入是否正确
		if(!encoder.matches(oldPassword,password.replace("{bcrypt}",""))){
			flag = -1;
			return flag;
		}else{
			if(newPassword.equals(oldPassword)){
				//新旧密码相同
				flag = 1;
				return flag;
			}
		}
		flag = 200;
		userEntity.setPassword(newPassword);
		updateUser(userEntity);
		return flag;
	}

	/**
	 * 手机端注册
	 * @param loginName
	 * @param password
	 * @param houseId
	 */
	@Override
	public String register(String loginName, String password, Integer houseId) {
		//1.判断用户表是否有数据，没有则新增，有则跳过
		UserEntity existUser = userDao.getUserByLoginName(loginName);
		if(null != existUser){
			return String.format("手机号码：%s,已注册！请不用重复注册！",loginName);
		}
		UserEntity userEntity = new UserEntity();
		if( null == existUser) {
			userEntity.setLoginName(loginName); //用户名
			userEntity.setName(loginName);//用户名
			userEntity.setMobile(loginName);//手机号码
			userEntity.setPassword("{bcrypt}"+new BCryptPasswordEncoder().encode(password));
			userEntity.setStatus("0");
			userEntity.setAuthStatus("0");
			userEntity.setSource("1");
			userEntity.setCreateTime(new Date());
			Residence residence = residenceMapper.getResidenceByHouseId(houseId);
			userEntity.setRid(residence.getId().toString());
			userDao.insertUser(userEntity);

			//添加用户角色关联表
			List<RelationEntity> relationEntityList = new ArrayList<RelationEntity>();
			RelationEntity relationEntity = new RelationEntity();
			relationEntity.setRoleId(2);
			relationEntity.setUserId(userEntity.getId());
			relationEntityList.add(relationEntity);
			relationDao.insertRelations(relationEntityList);
		}else {
//			//同一个手机号注册第二个小区
//			Residence residence = residenceMapper.getResidenceByHouseId(houseId);
//
//			userEntity.setRid(existUser.getRid()+","+residence.getId());
//			//1.如果小区一样，则不做处理，提示已经注册
//
//			//2.如果小区不一样，则修改对应权限小区
			userEntity = existUser;
		}
		//2.判断住户表中是否存在手机号码，如果存在，则更新住户的id为当前用户id
		List<HouseholdBean> list = householdDao.getHouseholdByMobile(userEntity.getMobile());

		if(null == list || list.size() == 0) {
			//添加住户信息
			HouseholdBean householdEntity = new HouseholdBean();
			householdEntity.setUserId(userEntity.getId());//用户id
			householdEntity.setHouseId(houseId);//房屋id
			householdEntity.setMobile(loginName);//手机号码
			householdEntity.setStatus("1");//0禁用，1启用
			householdEntity.setAuthStatus("0");//0未认证,1已认证
			householdEntity.setCreateTime(new Date());
			householdDao.insert(householdEntity);
		}else{
			HouseholdBean household = list.get(0);
			household.setUserId(userEntity.getId());
			householdDao.updateByPrimaryKeySelective(household);
		}
		return String.format("手机号码：%s,注册成功！",loginName);
	}

	@Override
	public List<UserEntity> getMaintenanceList(Integer residenceId) {
		return userDao.getMaintenanceList(residenceId);
	}
}
